Page({
  data: {
    records: []
  },

  onLoad() {
    this.loadRecords();
  },

  // 加载治疗记录
  loadRecords() {
    const records = wx.getStorageSync('treatmentRecords') || [];
    this.setData({ records: records });
  },

  // 导出数据
  exportData() {
    const records = this.data.records;
    
    if (records.length === 0) {
      wx.showToast({
        title: '暂无数据可导出',
        icon: 'none'
      });
      return;
    }
    
    // 生成CSV格式数据
    let csvContent = '治疗时间,治疗模式,电流强度(mA),设定时长(分钟),实际时长(分钟),频率(Hz),完成状态\n';
    
    records.forEach(record => {
      const date = new Date(record.date).toLocaleString();
      const mode = record.params.mode;
      const current = record.params.current;
      const plannedTime = record.params.time;
      const actualTime = record.duration.toFixed(1);
      const frequency = record.params.frequency || '';
      const status = record.completed ? '已完成' : '未完成';
      
      csvContent += `${date},${mode},${current},${plannedTime},${actualTime},${frequency},${status}\n`;
    });
    
    // 保存到临时文件
    const fs = wx.getFileSystemManager();
    const filePath = `${wx.env.USER_DATA_PATH}/treatment_records.csv`;
    
    fs.writeFile({
      filePath: filePath,
      data: csvContent,
      encoding: 'utf8',
      success: () => {
        wx.showModal({
          title: '导出成功',
          content: '数据已导出，是否分享？',
          success: (res) => {
            if (res.confirm) {
              wx.shareFileMessage({
                filePath: filePath,
                fileName: '治疗记录.csv'
              });
            }
          }
        });
      },
      fail: () => {
        wx.showToast({
          title: '导出失败',
          icon: 'none'
        });
      }
    });
  }
});